/**
 * 用于连接哔哩哔哩直播开放平台的类
 */
function biliLive(accessKeyId, data = {}) {
	const url = "https://live-open.biliapi.com/v2/app/start" //开放接口
	const method = "POST"
	const xhr = new XMLHttpRequest()
	return new Promise((resolve, reject) => {
		xhr.open(method, url)
		xhr.addEventListener("loadend", function (result) {
			xhr.status >= 200 && xhr.status < 300 ? resolve(JSON.parse(xhr.response)) : resolve(new Error(xhr.response))
		})
		xhr.addEventListener("error", function (err) {
			reject(err)
		})

		const dataObj = getEncodeHeader(data, accessKeyId)
		for (const key in dataObj) {
			xhr.setRequestHeader(key, dataObj[key])
		}
		xhr.send(JSON.stringify(data))
	})
}

function getEncodeHeader(params = {}, appKey) {
	const timestamp = parseInt(Date.now() / 1000 + "")
	const nonce = parseInt(Math.random() * 100000 + "") + timestamp
	const paramsMD5 = hexMD5(JSON.stringify(params))
	const header = {
		"x-bili-accesskeyid": appKey,
		"x-bili-content-md5": paramsMD5,
		"x-bili-signature-method": "HMAC-SHA256",
		"x-bili-signature-nonce": nonce + "",
		"x-bili-signature-version": "1.0",
		"x-bili-timestamp": timestamp
	}
	const data = []
	for (const key in header) {
		data.push(`${key}:${header[key]}`)
	}

	const signature = sha256(data.join("\n"))
	return {
		Accept: "application/json",
		"Content-Type": "application/json",
		...header,
		Authorization: signature
	}
}
